<script setup>

import PageHeader from "@/components/PageHeader.vue";
import {useUserStore} from "@/stores/UserStore.js";
import {onMounted, reactive, ref, watch} from "vue";
import axios from "axios";
import router from "@/router/index.js";
import PageFooter from "@/components/PageFooter.vue";

const props = {
  t1: "数据",
  t2: "动态",
  t1Url: {name: ''},
  t2Url: {name: ''}
}

const userStore = useUserStore()
const gameList = ref({})
const player = reactive({
  time: 0,
  lv: 0,
  tp: 0,
  img: "",
  personaName: "",
  avatar: "",
  personaState: 0,
  gameExtraInfo: '',
  gameID: 0
})

const GameInfo = reactive([])
const FZ = ref([])

onMounted(async () => {
  FZ.value = (await axios.get(`http://localhost:8081/user/v1/count/${userStore.getUserInfo.id}`)).data
})

const fetchSteamLv = (steamId) => {
  axios.get("http://localhost:3000/Steam", {
    params: {steamID: steamId},
  }).then(response => {
    player.lv = response.data.Steam?.response?.player_level
  })
}

const fetchGameData = (steamId) => {
  axios.get("http://localhost:3000/PlayerGameList", {
    params: {steamID: steamId},
  }).then(response => {
    response?.data.Steam.response.games.forEach((game, index) => {
      setTimeout(() => {
        axios.get("http://localhost:3000/app", {
          params: {AppId: game.appid}
        }).then(response => {

          const get = response.data?.reply[game.appid].data;

          GameInfo.push({
            img: get.header_image,
            total_time: Math.round(game.playtime_forever / 60),
            RTime_last_played: game.rtime_last_played,
            name: game.name,
            playtime_2weeks: game?.playtime_2weeks || 0,
            app_id: game?.appid,
            price: get?.price_overview?.final,
          });

          GameInfo.sort((a, b) => {
            if (a.playtime_2weeks !== b.playtime_2weeks) {
              return b.playtime_2weeks - a.playtime_2weeks; // 先按 playtime_2weeks 降序
            }
            return b.total_time - a.total_time; // 再按 total_time 降序
          });

          userStore.setGames(GameInfo)
        });
      }, index * 1000); // 每个请求间隔 1000ms
    });
  })
}

const fetchPlayerData = (steamId) => {
  axios.get(`http://localhost:3000/Player`, {
    params: {steamID: steamId}
  }).then(res => {
    gameList.value = res.data;

    let tempTime = gameList.value?.Player?.response?.games?.reduce((sum, game) => {
      return sum + game.playtime_forever / 60;
    }, 0) || 0;
    player.time = Math.round(tempTime)
  }).catch(error => {
    console.error("请求失败：", error);
  });
};

const getPlayerInfo = (steamId) => {
  axios.get(`http://localhost:3000/PlayerInfo`, {
    params: {
      steamID: steamId
    }
  }).then(res => {
    const pl = res.data?.response.players[0];
    player.avatar = pl.avatar
    player.personaName = pl.personaname
    player.personaState = pl.personastate
    player.gameExtraInfo = pl?.gameextrainfo
    player.gameID = pl.gameid
  })
}

const getTp = () => {
  GameInfo.forEach(item => {
    console.log(item.price)
    player.tp += item.price / 100
  })
}
getTp()
watch(
    () => userStore.getUserInfo?.steamId,
    (newSteamId) => {
      if (newSteamId) {
        fetchPlayerData(newSteamId);

        // 只有在 userStore.getGame 为空时才调用 fetchGameData
        if (!Array.isArray(userStore.getGame) || userStore.getGame.length === 0) {
          fetchGameData(newSteamId);
        }

        fetchSteamLv(newSteamId);
        getPlayerInfo(newSteamId);

      }
    },
    {immediate: true}
);

watch(
    () => userStore.getGame,
    (newVal) => {
      if (Array.isArray(newVal)) {
        GameInfo.splice(0, GameInfo.length, ...newVal);
      }
    },
    {immediate: true}
);

</script>

<template>
  <PageHeader :t1 = "props.t1" :t2 = "props.t2" :t1Url = "props.t1Url" :t2Url = "props.t2Url" :pl = "true" />
  <div class = "UserInfo  d-flex p-2">
    <div class = "UserImg p-2">
      <img :src = "userStore.getUserInfo.userAvatar" width = "64" alt = "">
    </div>
    <div class = "info ">
      <p>{{ userStore.getUserInfo?.name }}</p>
      <p>{{ userStore.getUserInfo?.signature }}</p>
    </div>
  </div>
  <div class = "data  mt-1 p-2">
    <div class = "concern acc ">
      <span>{{ FZ.Follow }}</span>
      <p>关注</p>
    </div>
    <div class = "fans acc ">
      <span>{{ FZ.Fans }}</span>
      <p>粉丝</p>
    </div>
    <div class = "collection acc " @click = "router.push({name:'Collection'})">
      <span>{{ FZ.Collection }}</span>
      <p>收藏</p>
    </div>
    <div class = "history acc " @click = "router.push({name:'Release'})">
      <span>{{ FZ.History }}</span>
      <p>历史浏览</p>
    </div>
  </div>
  <div class = "steamInfo  mt-2">
    <div class = "Img_Name p-2">
      <div class = "dInfo "><img :src = "player.avatar"
                                 width = "42" alt = ""><span class = "UserName">
        {{ player.personaName ? player.personaName : "暂未绑定" }}
      </span>
        <span class = "lv">Lv.<span>{{ player.lv ? player.lv : '' }}</span></span>
        <span class = "status"> {{ player.personaState === 0 ? "离线" : '在线' }}</span>
        <div class = "nowPlay" v-if = "player.gameExtraInfo">正在玩: {{ player.gameExtraInfo }}</div>
        <div class = "nowPlay" v-if = "!player.gameExtraInfo">发呆</div>
      </div>

    </div>
    <div class = " mt-1 statistics">
      <div class = "GamePrice acx ">
        <span>{{ player.tp }}</span>
        <p>账号价值</p>
      </div>
      <div class = "GameTime acx ">
        <span>{{ player.time || 0 }}</span>
        <p>游戏时长</p>
      </div>
      <div class = "GameCount acx ">
        <span>{{ gameList?.Player?.response?.game_count ? gameList?.Player?.response?.game_count : 0 }}</span>
        <p>游戏数量</p>
      </div>
    </div>
    <div class = "GameList  mt-3">
      <span class = ""><svg class = "icon" viewBox = "0 0 1024 1024"
                            xmlns = "http://www.w3.org/2000/svg" width = "22" height = "22"><path
          d = "M511.104 0C242.261333 0 21.802667 207.36 0.938667 470.912l274.432 113.408a144.512 144.512 0 0 1 81.578666-25.173333c2.688 0 5.333333 0.170667 8.021334 0.256l122.069333-176.725334V380.16a193.194667 193.194667 0 0 1 193.024-193.024c106.410667 0 193.024 86.656 193.024 193.152s-86.613333 193.066667-193.024 193.066667h-4.48l-173.909333 124.202666c0 2.218667 0.170667 4.48 0.170666 6.784a144.725333 144.725333 0 0 1-144.64 144.896 145.578667 145.578667 0 0 1-142.122666-116.352L18.602667 651.52C79.445333 866.432 276.736 1024 511.104 1024c282.752 0 511.957333-229.248 511.957333-512S793.813333 0 511.104 0zM321.706667 776.96l-62.848-26.026667c11.178667 23.168 30.464 42.624 56.064 53.333334a108.842667 108.842667 0 0 0 142.378666-141.824 108.672 108.672 0 0 0-138.88-60.288l64.981334 26.88a80.128 80.128 0 0 1-61.653334 147.925333H321.706667z m487.04-396.928a128.810667 128.810667 0 0 0-128.64-128.64 128.64 128.64 0 1 0 128.64 128.64z m-224.981334-0.213333a96.597333 96.597333 0 1 1 193.322667 0 96.725333 96.725333 0 0 1-96.682667 96.64 96.597333 96.597333 0 0 1-96.64-96.64z"
          fill = "#2c2c2c"></path></svg><span class = "hasGame">拥有游戏</span></span>
      <div class = "List mt-1">
        <ul class = "GUL ">
          <li class = "p-2 d-flex" v-for = "item in GameInfo" :key = "item.app_id"
              @click = "router.push({path:`/GameDt/${item.app_id}/1/-1`})">
            <div class = "GameHeader">
              <img
                  :src = "item.img" width = "140"
                  alt = "CS2" />
            </div>
            <div class = "GameInfo">
              <span class = "GameName">{{ item.name }}</span>
              <div class = "GameTime d-flex">
                <div>
                  <span>{{ item.total_time }}&nbsp;h</span>
                </div>
                <div class = "">
                  <span v-if = "item.app_id === player.gameID">正在游玩</span>
                  <span v-else-if = "item.playtime_2weeks >= 60">{{
                      item.playtime_2weeks > 60 ? Math.round(item.playtime_2weeks / 60) : item.playtime_2weeks
                    }}&nbsp;h</span>
                  <span v-else-if = "item.playtime_2weeks < 60">{{
                      item.playtime_2weeks > 60 ? Math.round(item.playtime_2weeks / 60) : item.playtime_2weeks
                    }}&nbsp;m</span>
                </div>
              </div>
              <div class = "MyProgress"
                   :style = "{'--progress': ((item.playtime_2weeks / 60) || item.total_time)  + '%'}"></div>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>
  <PageFooter />
</template>

<style scoped>
.UserInfo {
  margin-top: 60px;
}

svg {
  margin: 0;
  padding: 0;
}

.UserImg {
  width: 72px;
  height: 72px;
  border-radius: 80px;
  overflow: hidden;
  position: relative;
  border: 1px solid gray;

}

.UserImg img {
  position: absolute;
  top: -5px;
  left: 5px;
}

.info {
  margin-left: 10px;
}

.info p {
  margin: 10px 0;
  font-size: 18px;
}

.info p:last-child {
  color: gray;
  font-size: 14px;
}

.steamInfo {
  height: 200px;
}

.dInfo {
  height: 70px;
  background-color: rgba(13, 19, 14, 0.6);
}

.UserName {
  color: white;
  font-size: 18px;
  margin-left: 4px;
}

.status {
  font-size: 14px;
  margin-left: 6px;
}

.statistics {
  margin: auto;
  width: 96%;
  display: flex;
  background-color: rgba(14, 8, 8, 0.6);
}

.statistics div p {
  color: white;
}

.acx {
  width: 80px;
}

.acx span {
  font-size: 20px;
  color: white;
}

.acx p {
  margin: 0;
  font-size: 14px;
  color: gray;
}

.acx:not(:first-child) {
  margin-left: 20px;
}

.GameList {
  width: 96%;
  margin: auto;
}

.hasGame {
  margin: 0;
  padding: 0;
}

.GUL {
  margin: 0;
  padding: 0;
}

.GUL li {
  margin: 0;
  padding: 0;
  border-bottom: 1px solid black;
}

.GameHeader {
  width: 140px;
  border-radius: 4px;
  overflow: hidden;
}

.GameInfo {
  position: relative;
  margin-left: 10px;
  width: 220px;
}

.nowPlay {
  color: white;
  width: 100%;
  overflow: hidden;
  height: 20px;
  font-size: 12px;
  line-height: 24px;
}

.GameName {
  display: inline-block;
  font-size: 14px;
  width: 100%;
  height: 19px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.GameTime {
  position: relative;
  font-size: 14px;
  color: gray;
}

.GameTime div:last-child {
  position: absolute;
  right: 0;
}

hr {
  position: relative;
  top: -1px;
  margin: 0 auto;
  width: 96%;
}

@property --progress {
  syntax: '<percentage>';
  inherits: false;
  initial-value: 0%;
}

.MyProgress {
  margin: 0;
  position: absolute;
  width: 224px;
  height: 8px;
  border-radius: 15px;
  top: 80%;
  transition: .3s --progress;
  background: rgba(128, 128, 128, 0.2) linear-gradient(90deg, #0f0, #0ff var(--progress), transparent 0);
}

.acc {
  text-align: center;
  width: 80px;
  cursor: pointer;
}

.acc span {
  font-size: 18px;
}

.acc p {
  margin: 0;
  padding: 0;
  font-size: 16px;
  color: gray;
}

.data {
  display: flex;
  justify-content: space-between;
}

.lv {
  margin-left: 10px;
}
</style>